package com.ajx.platform.buildingmronitor.service.impl;

import com.ajx.platform.buildingmronitor.model.HightBuildCameraEvent;
import com.ajx.platform.buildingmronitor.model.VideoDTO;
import com.ajx.platform.buildingmronitor.service.HightBuildCameraEventService;
import com.ajx.platform.buildingmronitor.service.HightBuildCameraService;
import com.ajx.platform.buildingmronitor.service.ReceiveVideoService;
import com.ajx.platform.buildingmronitor.utils.ByteUtil;
import com.ajx.platform.buildingmronitor.utils.DateUtils;
import com.ajx.platform.buildingmronitor.utils.FileUtil;
import com.anjuxing.platform.common.base.User;
import com.anjuxing.platform.common.exception.ServiceException;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service("receiveVideoService")
@Transactional(readOnly = false, rollbackFor = ServiceException.class)
public class ReceiveVideoServiceImpl implements ReceiveVideoService {

    Logger logger = LoggerFactory.getLogger(ReceiveVideoServiceImpl.class);

    @Value("${file.upload.path1}")
    private String videoRootPath;

    @Autowired
    HightBuildCameraService hightBuildCameraService;
    @Autowired
    HightBuildCameraEventService hightBuildCameraEventService;

    /** 接收相机客户端发送的视频文件（客户端分包发送）
     *
     * devSN 设备序列号
     * video 视频名称
     * videoPos 当前传输录像的位置（开始位置）
     * videoLength 录像文件总长度(分包传输前的总长度)
     **/
    @Override
    public Map receiveVideo(HttpServletRequest request, VideoDTO receiveParam) throws Exception{

        String devSN = receiveParam.getDevSN();
        String video = receiveParam.getVideo();
        int videoPos = receiveParam.getVideoPos();

        //logger.info(devSN+":::"+video+":::"+videoPos+":::"+videoLength+":::"+eventName+":::"+devName+":::"+devID);
        //System.out.println(devSN+":::"+video+":::"+videoPos);
        logger.info(videoRootPath);
        String localFilePath = videoRootPath;
        Map responseMap = new HashMap();
        try {
            // 接收分包传输的视频文件
            byte[] temp = ByteUtil.toByteArray(request.getInputStream());
            String fileName = video+".mp4";
            File tempfiles = null;
            if (videoPos == 0) {//第一次分包的传输
                String groupId = hightBuildCameraService.findGroupCamera(devSN);
                if (StringUtils.isNotBlank(groupId)) {
                    // 同一组，同一时间点（相差10s的为一组事件）
                    Map param = new HashMap();
                    Date currentDate = com.anjuxing.platform.common.util.DateUtils.getCurrentTime();
                    param.put("groupId",groupId);
                    param.put("currentDate",currentDate);
                    HightBuildCameraEvent event = hightBuildCameraEventService.getEventByParam(param);
                    if (event == null) {
                        //System.out.println("event == null");
                        HightBuildCameraEvent entity = new HightBuildCameraEvent();
                        localFilePath = videoRootPath+DateUtils.getCurrentTimeStr()+"/";
                        entity.preInsert(new User());
                        entity.setGroupId(groupId);
                        entity.setLocalFilePath(localFilePath);
                        entity.setSnapshotTime(currentDate);
                        hightBuildCameraEventService.save(entity);
                        //取得Application对象
                        ServletContext application=request.getServletContext();
                        // localFilePath 保存到application中
                        application.setAttribute("localFilePath",localFilePath);
                        //System.out.println("11111111111:"+application.getAttribute("localFilePath"));
                    }else {
                        localFilePath = event.getLocalFilePath();
                        // localFilePath 保存到session中
                        ServletContext application=request.getServletContext();
                        application.setAttribute("localFilePath",localFilePath);
                        //System.out.println("222222222:"+application.getAttribute("localFilePath"));
                    }
                }else {logger.warn("请设置相机组别！");}
                tempfiles = FileUtil.createFile(localFilePath,fileName);
            }else {
                // 从application中取localFilePath
                ServletContext application=request.getServletContext();
                Object obj = application.getAttribute("localFilePath");
                if (!ObjectUtils.isEmpty(obj)) {
                    localFilePath = obj.toString();
                    //System.out.println("333333333333:"+localFilePath);
                }
                tempfiles = new File(localFilePath+fileName);
            }
            RandomAccessFile rfile = new RandomAccessFile(tempfiles, "rw");
            rfile.seek(videoPos);
            rfile.write(temp);
            rfile.close();
            responseMap.put("msg","SUCCESS");
            responseMap.put("resp",true);
            responseMap.put("statusCode",200);
            responseMap.put("value",videoPos+temp.length);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return responseMap;
    }
}